import { DatePicker } from 'element-ui'

export const isBoolean = (obj) => {
  return typeof obj === 'boolean'
}
export const isNumber = (obj) => {
  return typeof obj === 'number' && !isNaN(obj)
}
export const isString = (obj) => {
  return typeof obj === 'string'
}
export const isInteger = function(obj) {
  return (obj | 0) === obj
}
export const isNull = function(obj) {
  return obj === undefined || obj === null
}
export const isNoValue = function(obj) {
  return obj === undefined || obj === null || obj === ''
}
export const getTime = (date, getSec) => {
  if (date === null) return
  date = new Date(date)
  if (date.toString() === 'Invalid Date') return
  let hour = date.getHours()
  let min = date.getMinutes()
  hour = hour > 9 ? hour : `0${hour}`
  min = min > 9 ? min : `0${min}`
  let result = `${hour}:${min}`
  if (getSec) {
    let sec = date.getSeconds()
    sec = sec > 9 ? sec : `0${sec}`
    result = `${hour}:${min}:${sec}`
  }
  return result
}
// 格式化日期
export const formatDate = (date) => {
  if (date === null) return
  date = new Date(date)
  if (date.toString() === 'Invalid Date') return
  let m = (date.getMonth() + 1).toString()
  let d = date.getDate().toString()
  m = m.length >= 2 ? m : '0' + m
  d = d.length >= 2 ? d : '0' + d
  return date.getFullYear() + '-' + m + '-' + d
}
export const isValidDate = (date) => {
  if (date === null) return false
  date = new Date(date)
  return date.toString() !== 'Invalid Date'
}
export const formatDateAndTime = (date) => {
  if (date === null) return
  date = new Date(date)
  if (date.toString() === 'Invalid Date') return
  const dateStr = formatDate(date)
  const timeStr = getTime(date)
  return `${dateStr} ${timeStr}`
}
export const setTimeToDate = (timeStr, date) => {
  date = new Date(date)
  if (date.toString() === 'Invalid Date') return
  timeStr = timeStr.split(':')
  date.setHours(parseInt(timeStr[0]))
  date.setMinutes(parseInt(timeStr[1]))
  return date
}
// 获取现在的年月日及明天
export const nowDate = (num) => {
  const date = new Date()
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  let day = date.getDate() + num
  if (month === 2) {
    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
      if (day > 29) {
        day = 1
        month = month + 1
      }
    } else {
      if (day > 28) {
        day = 1
        month = month + 1
      }
    }
  } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
    if (day > 31) {
      day = 1
      month = month + 1
    }
  } else {
    const dayN = 30 - Math.abs(day)
    day = dayN
  }
  if (month < 10) {
    month = '0' + month
  }
  return `${year}-${month}-${day}`
}
// 获取最近1个月内
export const recentDate = (Num) => {
  const date = new Date()
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  if (month < 10) {
    month = '0' + month
  }
  let day = date.getDate() - Num
  if (day < 0) {
    if (month < 10) {
      month = '0' + (month - 1)
    }
    if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
      month = '02'
      const dayN = 29 - Math.abs(day)
      day = dayN
    } else if (month === '01' || month === '03' || month === '05' || month === '07' || month === '08' || month === 10 || month === 12) {
      const dayN = 31 - Math.abs(day)
      day = dayN
    } else {
      const dayN = 30 - Math.abs(day)
      day = dayN
    }
  }
  const data = `${year}-${month}-${day}`
  return data
}
// 获取最近90天
export const nineDate = () => {
  const date = new Date()
  let year = date.getFullYear()
  let month = date.getMonth() - 2
  if (month < 10) {
    if (month < 0) {
      year = date.getFullYear() - 1
      month = 12 - date.getMonth()
    }
    month = '0' + month
  }
  const day = date.getDate()
  // if (day < 0) {
  //   month = month - 1
  //   if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
  //     month = 2
  //     const dayN = 29 - Math.abs(day)
  //     day = dayN
  //   } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
  //     const dayN = 31 - Math.abs(day)
  //     day = dayN
  //   } else {
  //     const dayN = 30 - Math.abs(day)
  //     day = dayN
  //   }
  // }
  const data = `${year}-${month}-${day}`
  return data
}
// export const calculateWeek = (curDate) => {
//   var day = curDate.getDay()
//   // if (day == 0) {
//   //     day = 7;
//   // }
//   let daysArr = []
//   var str = this.joinDate(curDate.getFullYear(), curDate.getMonth() + 1, curDate.getDate())
//   str = str.replace(/\./g, "/")
//   for (var i = day - 1; i >= 0; i--) {
//     var d = new Date(str)
//     d.setDate(d.getDate() - i)
//     daysArr.push(d)
//     return daysArr
//   }
//   for (var i = 1; i <= 7 - day; i++) {
//     const d = new Date(str)
//     d.setDate(d.getDate() + i)
//     daysArr.push(d)
//     return daysArr
//   }
// }

// 每周第一天
export const getWeeK = (num) => {
  var Nowdate = new Date()
  // var year = Nowdate.getFullYear()
  var WeekFirstDay = new Date(Nowdate - (Nowdate.getDay() - 1) * 86400000)
  var WeekLastDay = new Date((WeekFirstDay / 1000 + num * 86400) * 1000)
  var M = Number(WeekLastDay.getMonth()) + 1
  if (M < 10) {
    M = '0' + M
  }
  return WeekLastDay.getFullYear() + '-' + M + '-' + (WeekLastDay.getDate())
}
//
// 获取星期
export const week = (num) => {
  const date = new Date()
  if (date.getDay() + num === 0) {
    return '星期天'
  } else if (date.getDay() + num === 1) {
    return '星期一'
  } else if (date.getDay() + num === 2) {
    return '星期二'
  } else if (date.getDay() + num === 3) {
    return '星期三'
  } else if (date.getDay() + num === 4) {
    return '星期四'
  } else if (date.getDay() + num === 5) {
    return '星期五'
  } else if (date.getDay() + num === 6) {
    return '星期六'
  }
}
// 获取年月现在日
export const startYMD = (month) => {
  const date = new Date()
  const year = date.getFullYear()
  const day = 1
  const data = `${year}-${month}-${day}`
  return data
}
// 获取最年月最后一日
export const endYMD = (month) => {
  const date = new Date()
  const year = date.getFullYear()
  // var month = date.getMonth()
  let day = 30
  if (year % 4 === 0 && year % 100 !== 0 || year % 400 === 0) {
    month = 2
    day = 29
  } else if (month === 1 || month === 3 || month === 5 || month === 7 || month === 8 || month === 10 || month === 12) {
    day = 31
  } else if (month === 4 || month === 6 || month === 9 || month === 11) {
    day = 30
  } else {
    day = 28
  }
  const data = `${year}-${month}-${day}`
  return data
}

// 获取本月最后一天
export const getLstMonthDay = () => {
  var Nowdate = new Date()
  var MonthNextFirstDay = new Date(Nowdate.getYear(), Nowdate.getMonth() + 1, 1)
  var MonthLastDay = new Date(MonthNextFirstDay - 86400000)
  return MonthLastDay.getDate()
}
// 新老客户百分比计算
// export const getNewOldDate = (newCus, oldCus, tot) => {
//   return
// }

// 获取年月
export const currentYM = () => {
  const date = new Date()
  const year = date.getFullYear()
  let month = date.getMonth() + 1
  if (month < 10) {
    month = '0' + month
  }
  const data = `${year}-${month}`
  return data
}

// 切割最后一位转数字
export const subStr = (str) => {
  return Number(str.slice(0, -1))
}

export const isEmptyObj = (obj) => {
  for (const obj1 in obj) {
    return false
  }
  return true
}
// 截取字符串
export const strData = (str) => {
  return str.split(' ')[1]
}

// 除法
export const accDiv = (arg1, arg2) => {
  let t1 = 0
  let t2 = 0
  var r1, r2
  try {
    t1 = arg1.toString().split('.')[1].length
  } catch (e) {
    return false
  }
  try {
    t2 = arg2.toString().split('.')[1].length
  } catch (e) {
    return false
  }
  r1 = Number(arg1.toString().replace('.', ''))
  r2 = Number(arg2.toString().replace('.', ''))
  return accMul((r1 / r2), Math.pow(10, t2 - t1))
}

// 乘法
export const accMul = (arg1, arg2) => {
  let m = 0
  const s1 = arg1.toString()
  const s2 = arg2.toString()
  try {
    m += s1.split('.')[1].length
  } catch (e) {
    return false
  }
  try {
    m += s2.split('.')[1].length
  } catch (e) {
    return false
  }
  return Number(s1.replace('.', '')) * Number(s2.replace('.', '')) / Math.pow(10, m)
}

// 加法
export const accAdd = (arg1, arg2) => {
  var r1, r2, m
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  return (arg1 * m + arg2 * m) / m
}

// 减法
export const accSub = (arg1, arg2) => {
  var r1, r2, m, n
  try {
    r1 = arg1.toString().split('.')[1].length
  } catch (e) {
    r1 = 0
  }
  try {
    r2 = arg2.toString().split('.')[1].length
  } catch (e) {
    r2 = 0
  }
  m = Math.pow(10, Math.max(r1, r2))
  n = (r1 >= r2) ? r1 : r2
  return ((arg1 * m - arg2 * m) / m).toFixed(n)
}

// 将一维数组转换为二维数组
export const transferTo2DArray = function(arr, col) {
  const arr2 = []
  const row = Math.ceil(arr.length / col)
  for (let i = 0; i < row; i++) {
    arr2[i] = []
    for (let j = 0; j < col; j++) {
      if (arr[i * col + j]) {
        arr2[i][j] = arr[i * col + j]
      }
    }
  }
  return arr2
}

export const genID = (randomLength = 6) => {
  return Number(Math.random().toString().substr(3, randomLength) + Date.now()).toString(36)
}

export const maskStr = (str, start, end, char = '*') => {
  if (typeof str !== 'string') return
  const len = str.length - start - end
  let xing = ''
  for (let i = 0; i < len; i++) {
    xing += char
  }
  return str.substring(0, start) + xing + str.substring(str.length - end)
}

export const msToTime = (ms, keepHour = true, useCH = false) => {
  let t = ''
  const s = Math.round(ms / 1000)
  if (s > 0) {
    const hour = Math.floor(s / 3600)
    const min = Math.floor(s / 60) % 60
    const sec = s % 60
    const split = useCH ? ['时', '分', '秒'] : new Array(2).fill(':')
    if (hour < 10) {
      if (keepHour || t > 0) {
        t += '0' + hour + split[0]
      }
    } else {
      t += hour + split[0]
    }

    if (min < 10 && min >= 0) {
      t += '0'
    }
    t += min + split[1]
    if (sec < 10 && sec >= 0) {
      t += '0'
    }
    t += sec + (useCH ? split[2] : '')
    return t
  } else {
    return '00:00:00'
  }
}

// export const loadJS = (url) => {
//   return new Promise((resolve, reject) => {
//     if (!url) {
//       reject(new Error('a js url is required'))
//     } else {
//       getScript(url)
//         .done(function(script, textStatus) {
//           resolve()
//         })
//         .fail(function(jqxhr, settings, exception) {
//           console.log(exception)
//           reject(new Error('load js fail, src is:' + url))
//         })
//     }
//   })
// }

export const loadCSS = (url) => {
  return new Promise((resolve, reject) => {
    if (!url) {
      reject(new Error('a css url is required'))
    } else {
      ('<link>')
        .attr({
          rel: 'stylesheet',
          type: 'text/css',
          href: url
        })
        .appendTo('head')
      resolve()
    }
  })
}

export const calcPercent = (val, totalVal) => {
  if (totalVal === 0) return 0
  return parseFloat(accMul(val / totalVal, 100).toFixed(2))
}

export const checkPasswordStrength = (pw, oldPw) => {
  const result = {
    strength: 0,
    tooShort: false,
    invalid: false,
    samePassword: false,
    tooShortText: '密码长度需大于等于6位',
    invalidText: '密码只能由字母、数字、下划线和减号组成',
    samePasswordText: '与原密码相同'
  }
  if (oldPw && pw === oldPw) {
    result.samePassword = true
    return result
  }
  if (pw.length < 6) {
    result.tooShort = true
    return result
  }
  if (!/^[a-zA-Z0-9_-]+$/.test(pw)) {
    result.invalid = true
    return result
  }
  if (/[0-9]/.test(pw)) result.strength++ // 数字
  if (/[a-z]/.test(pw)) result.strength++ // 小写
  if (/[A-Z]/.test(pw)) result.strength++ // 大写
  if (/_|-/.test(pw)) result.strength++ // 下划线和减号
  return result
}

export const isLocalStorageSupport = () => {
  var storageType = 'localStorage'
  try {
    var supported = (storageType in window && window[storageType] !== null)

    // When Safari (OS X or iOS) is in private browsing mode, it appears as though localStorage
    // is available, but trying to call .setItem throws an exception.
    //
    // "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage
    // that exceeded the quota."
    var key = '__' + Math.round(Math.random() * 1e7)
    if (supported) {
      var webStorage = window[storageType]
      webStorage.setItem(key, '')
      webStorage.removeItem(key)
    }
    return supported
  } catch (e) {
    return false
  }
}
export const ranNum = () => {
  return Math.floor(Math.random() * 3)
}
export const formatPrice = (price) => {
  if (isNumber(price)) {
    return `￥${price.toFixed(2)}`
  }
}
export function toThousandslsFilter(num) {
  return (+num || 0).toString().replace(/^-?\d+/g, m => m.replace(/(?=(?!\b)(\d{3})+$)/g, ','))
}
